package com.example.common.resp;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Page;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "分页响应")
public class PageResp<T> implements Serializable {

    @Schema(description = "每页数量")
    private int size;

    @Schema(description = "页码")
    private int page;

    @Schema(description = "最后页")
    private int endPage;

    @Schema(description = "总数据量")
    private long total;

    @Schema(description = "数据集合")
    private List<T> data;

    public static PageResp empty() {
        return new PageResp<>(0, 0, 0, 0, Collections.emptyList());
    }

    public static <T> PageResp<T> listToPage(List<T> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            PageResp<T> searchResult = new PageResp<>();
            searchResult.setData(list);
            searchResult.setPage(1);
            searchResult.setEndPage(1);
            searchResult.setSize(list.size());
            searchResult.setTotal(list.size());
            return searchResult;
        }
        return new PageResp<>(0, 0, 0, 0, Collections.emptyList());
    }

    public static <T> PageResp<T> by(Page<T> pages) {
        if (pages.hasContent()) {
            PageResp<T> searchResult = new PageResp<>();
            searchResult.setData(pages.getContent());
            searchResult.setPage(pages.getNumber() + 1);
            searchResult.setEndPage(pages.getTotalPages());
            searchResult.setSize(pages.getSize());
            searchResult.setTotal(pages.getTotalElements());
            return searchResult;
        }
        return new PageResp<>(0, 0, 0, 0, Collections.emptyList());
    }

    public static <T> PageResp<T> of(Page pages, List<T> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            PageResp<T> searchResult = new PageResp<>();
            searchResult.setData(list);
            searchResult.setPage(pages.getNumber() + 1);
            searchResult.setEndPage(pages.getTotalPages());
            searchResult.setSize(pages.getSize());
            searchResult.setTotal(pages.getTotalElements());
            return searchResult;
        }
        return new PageResp<>(0, 0, 0, 0, Collections.emptyList());
    }
}
